import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get_storage/get_storage.dart';
import 'package:smart_translator/app/modules/videoCall/controller/utils.dart';
import 'package:smart_translator/app/modules/videoCall/views/showTime.dart';
import 'package:smart_translator/app/style/widget_style.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import 'package:tencent_rtc_sdk/trtc_cloud_video_view.dart';
import '../../../utils/CommonUtil.dart';
import '../../../views/controller/MineViewController.dart';
import 'video_call_footer.dart';
import '../controller/video_calling_controller.dart';

class VideoCallingView extends GetView<VideoCallingController> {
  const VideoCallingView({super.key});

  Widget _renderLocalView(valueKey) {
    return GestureDetector(
      key: valueKey,
      behavior: HitTestBehavior.opaque,
      child: TRTCCloudVideoView(
        key: valueKey,
        hitTestBehavior: PlatformViewHitTestBehavior.transparent,
        onViewCreated: (viewId) async {
          controller.displayLocalVideo(viewId);
          controller.callParams.localViewId = viewId;
        },
      ),
    );
    // if(controller.getStream.value ==true){
    //   return GestureDetector(
    //     key: valueKey,
    //     behavior: HitTestBehavior.opaque,
    //     child:
    //
    //     TRTCCloudVideoView(
    //       key: valueKey,
    //       hitTestBehavior: PlatformViewHitTestBehavior.transparent,
    //       onViewCreated: (viewId) async {
    //         controller.displayLocalVideo(viewId);
    //         controller.callParams.localViewId = viewId;
    //       },
    //     ),
    //   );
    // }else{
    //   return Text('loading');
    // }
  }

  Widget renderRemoteView(valueKey) {
    return GestureDetector(
      key: valueKey,
      behavior: HitTestBehavior.opaque,
      child: TRTCCloudVideoView(
        key: valueKey,
        hitTestBehavior: PlatformViewHitTestBehavior.transparent,
        onViewCreated: (viewId) async {
          controller.callParams.remoteViewId = viewId;
        },
      ),
    );
  }

  Widget avatar() {
    final mineViewController = Get.find<MineViewController>();
    final domainUrl = CommonUtil.getPicPre();
    final avatar = mineViewController.avatar.value;
    if (avatar != '') {
      return CircleAvatar(
        backgroundImage: NetworkImage('$domainUrl$avatar'),
        radius: 24,
      );
    }
    return Container(
      child: SvgPicture.asset('assets/images/icon_default_avatar_l.svg'),
      width: 48,
      height: 48,
    );
  }

  @override
  Widget build(BuildContext context) {
    ValueKey localVideoKey = ValueKey("local-video");
    ValueKey remoteVideoKey = ValueKey("remote-video");
    print('checkinitTrtc');
    controller.initTrtc();
    // if(controller.callType=='voice'){
    //   controller.startAudio();
    // }

    return SafeArea(
      top: false,
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Expanded(
              child: Container(
                color: Color(0xFFF2F4F7),
                child: Column(
                  children: [
                    Container(
                      height: 130.0,
                      width: Get.width,
                      padding: EdgeInsets.fromLTRB(16, 40, 18, 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      controller.chooseToLanguages();
                                      // controller.chooseFromLanguages();
                                    },
                                    child: Container(
                                      width: 128.w,
                                      height: 48.h,
                                      padding: EdgeInsets.all(8.w),
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        boxShadow: [
                                          CommonWidgets.getBoxShadow()
                                        ],
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(
                                          8,
                                        ), // Optional: add border radius
                                      ),
                                      child:Obx(()=>Text(
                                        controller.tgtLang.value,
                                        style: AppStyleThemeData.normal_bold,
                                        maxLines: 1, // 最多显示2行
                                        overflow: TextOverflow.ellipsis,
                                      ),),

                                    ),
                                  ),
                                ),
                                InkWell(
                                  onTap: (){
                                    controller.exchangeLang();
                                    },
                                  child: Container(
                                    height: 50,
                                    padding: EdgeInsets.all(14.w),
                                    margin: EdgeInsets.only(
                                      left: 16.w,
                                      right: 16.w,
                                    ),
                                    decoration: BoxDecoration(
                                      boxShadow: [
                                        CommonWidgets.getBoxShadow()
                                      ],
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(
                                        8,
                                      ), // Optional: add border radius
                                    ),
                                    child: Image.asset(
                                      'assets/images/icon_index_lang_exchange.png',
                                      width: 20.w,
                                      height: 20.h,
                                    ),
                                  ),
                                ),

                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      // controller.chooseToLanguages();
                                      controller.chooseFromLanguages();
                                    },
                                    child: Container(
                                      width: 128.w,
                                      height: 48.h,
                                      padding: EdgeInsets.all(8.w),
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        boxShadow: [
                                          CommonWidgets.getBoxShadow()
                                        ],
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(
                                          8,
                                        ), // Optional: add border radius
                                      ),
                                      child:Obx(()=>Text(
                                        controller.srcLang.value!,
                                        style: AppStyleThemeData.normal_bold,
                                        maxLines: 1, // 最多显示2行
                                        overflow: TextOverflow.ellipsis,
                                      ),),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Obx(()=> Visibility(
                            visible: (!controller.isEnter.value) || (controller.isLeave.value),
                            child: Container(
                              padding: EdgeInsets.fromLTRB(20, 0, 0, 0),
                              // width: 40,
                              child: InkWell(
                                onTap: () {
                                  videoUtil.shareInvite(controller.callType == 'voice');
                                },
                                child: Image.asset(
                                  'assets/images/icon_screen_share_realtime.png',
                                  width: 16.w,
                                  height: 16.h,
                                ),
                              ),
                            ),)),

                        ],
                      ),
                    ),
                    if (controller.callType == 'video')
                      Expanded(
                        child: Container(
                          color: Colors.black,
                          key: localVideoKey,
                          width: Get.width,
                          child: Stack(
                            key: localVideoKey,
                            children: <Widget>[
                              Obx(()=> Visibility(
                                visible: (controller.mainPerson !='admin')|| (controller.isOpenCamera.value),
                                child: Obx(()=> controller.mainPerson =='admin'?
                              _renderLocalView(localVideoKey):renderRemoteView(remoteVideoKey)),
                              ),),

                              // Positioned(
                              //   top: 20,
                              //   right: 20,
                              //   child: InkWell(
                              //     onTap: () {
                              //       controller.handleSwitchCamera();
                              //     },
                              //     child: Image.asset(
                              //       'assets/images/video_switch_font.png',
                              //       width: 24.w,
                              //       height: 24.h,
                              //     ),
                              //   ),
                              // ),
                              Positioned(
                                top: 300,
                                child: Container(
                                  height: 400,
                                  width: Get.width,
                                  padding: EdgeInsets.fromLTRB(16, 0, 16, 80),
                                  child: ListView(
                                    controller:
                                        controller.scrollController.value,
                                    children: [
                                      Obx(
                                        () => Column(
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          children:
                                              controller.textContext
                                                  .map((item) {
                                                    if(item['side'] =='left'){
                                                      return Opacity(
                                                          opacity: 0.8,
                                                          child:
                                                          Row(children: [
                                                            Container(
                                                              width: 260,
                                                              decoration: BoxDecoration(
                                                                color: Color(
                                                                  0xFF333333,
                                                                ), // 设置背景颜色
                                                                borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                  8.0,
                                                                ), // 设置圆角半径
                                                              ),
                                                              child: Column(
                                                                children: [
                                                                  Row(
                                                                    crossAxisAlignment: CrossAxisAlignment
                                                                        .start,
                                                                    children: [
                                                                      Expanded(
                                                                        child: Text(
                                                                          item['srcText'],
                                                                          style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize: controller.textSize.value.toDouble(),
                                                                          ),
                                                                        ),),
                                                                    ],),
                                                                  SizedBox(
                                                                    height: 6,),
                                                                  Row(
                                                                    children: [
                                                                      Expanded(
                                                                        child: Text(
                                                                          item['tgtText'],
                                                                          style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize: controller.textSize.value.toDouble(),
                                                                          ),
                                                                        ),),
                                                                    ],)

                                                                ],),
                                                              padding: EdgeInsets
                                                                  .fromLTRB(
                                                                16, 8, 16, 8,),
                                                              margin: EdgeInsets
                                                                  .fromLTRB(
                                                                16, 16, 16, 8,),
                                                            ),
                                                          ],)

                                                      );
                                                    }else{
                                                      return Opacity(
                                                          opacity: 0.6,
                                                          child:
                                                          Row(children: [
                                                            Expanded(child: SizedBox(width: double.infinity)),
                                                            Container(
                                                              width: 260,
                                                              decoration: BoxDecoration(
                                                                color: Color(
                                                                  0xFF0D65E6,
                                                                ), // 设置背景颜色
                                                                borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                  8.0,
                                                                ), // 设置圆角半径
                                                              ),
                                                              child: Column(
                                                                children: [
                                                                  Row(
                                                                    crossAxisAlignment: CrossAxisAlignment
                                                                        .start,
                                                                    children: [
                                                                      Expanded(
                                                                        child: Text(
                                                                          item['srcText'],
                                                                          style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize: controller.textSize.value.toDouble(),
                                                                          ),
                                                                        ),),
                                                                    ],),
                                                                  SizedBox(
                                                                    height: 6,),
                                                                  Row(
                                                                    children: [
                                                                      Expanded(
                                                                        child: Text(
                                                                          item['tgtText'],
                                                                          style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize: controller.textSize.value.toDouble(),
                                                                          ),
                                                                        ),),
                                                                    ],)

                                                                ],),
                                                              padding: EdgeInsets
                                                                  .fromLTRB(
                                                                16, 8, 8, 8,),
                                                              margin: EdgeInsets
                                                                  .fromLTRB(
                                                                16, 16, 0, 8,),
                                                            ),
                                                          ],)

                                                      );
                                                    }
                                              }
                                                  )
                                                  .toList(),
                                        ),
                                      ),
                                    ],
                                  ),
                                  // Obx(()=>Column(children:controller.textContext.map((item)=>Text(item)).toList(),))

                                  // ListView.builder(
                                  //     itemBuilder: (BuildContext context, int index){
                                  //       return Obx(()=>Text(controller.textContext[index]));
                                  //     }
                                  // )
                                ),
                              ),
                              Positioned(
                                top: 16,
                                right: 16,
                                child: InkWell(
                                  onTap: (){
                                    controller.switchView();
                                  },
                                  child: Container(
                                    width: 130,
                                    height: 160,
                                    decoration: BoxDecoration(
                                      color: Color(0xFF3F3F3F),
                                      // border: Border.all(color: Colors.white, width: 2),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child:Obx(()=>Visibility(
                                        visible:(controller.mainPerson !='admin')|| (controller.isOpenCamera.value),
                                        child: Obx(()=>controller.mainPerson =='admin'?
                                        renderRemoteView(remoteVideoKey):_renderLocalView(localVideoKey)))),
                                  )
                                ),

                              ),
                              Positioned(
                                top: 20,
                                right: 20,
                                child: InkWell(
                                  onTap: () {
                                    // controller.switchView();
                                    controller.handleSwitchCamera();
                                  },
                                  child: Image.asset(
                                    'assets/images/video_switch_font.png',
                                    width: 24.w,
                                    height: 24.h,
                                  ),
                                ),
                              ),
                              Obx(()=>
                                  Visibility(
                                    visible: controller.isEnter.value==false,
                                    child: Align(
                                      alignment: Alignment.center,
                                      child: Container(
                                        width: 224.w,
                                        height: 80.h,
                                        decoration: BoxDecoration(
                                          color: Colors.black,
                                          borderRadius:
                                          BorderRadius
                                              .circular(
                                            8.0,
                                          ), // 设置圆角半径
                                        ),
                                        padding: EdgeInsets.all(20.0),
                                        child: Text(
                                          style: TextStyle(color: Colors.white, fontSize: 16,),
                                          '正在等待好友接入…点击右上角“邀请”可以重新邀请。',
                                        ),
                                      ),
                                    ),
                                  ))
                             ,
                            ],
                          ),
                        ),
                      ),

                    if (controller.callType == 'voice')
                      Expanded(child:  Container(
                        width: Get.width,
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Stack(children: [
                                  // avatar(),
                                  Image.asset(
                                    'assets/images/video_invitee.png',
                                    width: 48,
                                    height: 48,
                                  ),
                                  Obx(()=>  Visibility(
                                      visible: controller.currentSpeaker.value=='left',
                                      child:Positioned(
                                        bottom: -5,
                                        right: -5,
                                        child: Image.asset(
                                          'assets/images/video_is_speaking.png',
                                          width: 24,
                                          height: 24,
                                        ),)))
                                ],),

                                SizedBox(width: 36),
                                Stack(children: [
                                  avatar(),

                                  // Image.asset(
                                  //   'assets/images/video_invitee.png',
                                  //   width: 48,
                                  //   height: 48,
                                  // ),
                                  Obx(()=>
                                      Visibility(
                                          visible: controller.currentSpeaker.value=='right',
                                          child:Positioned(
                                            bottom: -5,
                                            right: -5,
                                            child: Image.asset(
                                              'assets/images/video_is_speaking.png',
                                              width: 24,
                                              height: 24,
                                            ),))),
                                ],)
                              ],
                            ),
                            SizedBox(height: 10),
                            Center(
                              child:
                              Obx(()=>
                                  Text(
                                    (controller.isLeave.value == true)?'用户已离开房间':
                                    ((controller.isEnter.value==true)?'被邀请用户进入房间':'正在等待用户进入'),
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Color((0xFF999999)),
                                    ),
                                  ),),
                            ),

                            SizedBox(height: 8),
                            Expanded(child: ListView(
                              controller:
                              controller.scrollController.value,
                              children: [
                                Obx(
                                      () => Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children:
                                    controller.textContext
                                        .map((item) {
                                      if(item['side'] =='left'){
                                        return Opacity(
                                            opacity: 0.8,
                                            child:
                                                Column(children: [
                                                  Visibility(
                                                    visible: item['showTime'],
                                                    child:
                                                    Center(
                                                      child: Text(
                                                        '${item['currentTime'].hour.toString().padLeft(2,'0')}:${item['currentTime'].minute.toString().padLeft(2,'0')}:${item['currentTime'].second.toString().padLeft(2,'0')}',
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color: Color((0xFF999999)),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                  Row(children: [
                                                    Container(
                                                      width: 260,
                                                      decoration: BoxDecoration(
                                                        color: Colors.white,// 设置背景颜色
                                                        borderRadius:
                                                        BorderRadius
                                                            .circular(
                                                          8.0,
                                                        ), // 设置圆角半径
                                                      ),
                                                      child: Column(
                                                        children: [
                                                          Row(
                                                            crossAxisAlignment: CrossAxisAlignment
                                                                .start,
                                                            children: [
                                                              Expanded(
                                                                child: Text(
                                                                  item['srcText'],
                                                                  style: TextStyle(
                                                                    color: Color(
                                                                      0xFF333333,
                                                                    ),
                                                                    fontSize: controller.textSize.value.toDouble(),
                                                                  ),
                                                                ),),
                                                            ],),
                                                          SizedBox(
                                                            height: 6,),
                                                          Row(
                                                            children: [
                                                              Expanded(
                                                                child: Text(
                                                                  item['tgtText'],
                                                                  style: TextStyle(
                                                                    color: Color(
                                                                      0xFF333333,
                                                                    ),
                                                                    fontSize: controller.textSize.value.toDouble(),
                                                                  ),
                                                                ),),
                                                            ],)

                                                        ],),
                                                      padding: EdgeInsets
                                                          .fromLTRB(
                                                        16, 8, 8, 8,),
                                                      margin: EdgeInsets
                                                          .fromLTRB(
                                                        16, 16, 16, 8,),
                                                    ),
                                                  ],)
                                                ],),


                                        );
                                      }else{
                                        return Opacity(
                                            opacity: 1.0,
                                            child:
                                            Row(children: [
                                              Expanded(child: SizedBox(width: double.infinity)),
                                              Container(
                                                width: 260,
                                                decoration: BoxDecoration(
                                                  color: Color(
                                                    0xFFE3EFFF,
                                                  ), // 设置背景颜色
                                                  borderRadius:
                                                  BorderRadius
                                                      .circular(
                                                    8.0,
                                                  ), // 设置圆角半径
                                                ),
                                                child: Column(
                                                  children: [
                                                    Row(
                                                      crossAxisAlignment: CrossAxisAlignment
                                                          .start,
                                                      children: [
                                                        Expanded(
                                                          child: Text(
                                                            item['srcText'],
                                                            style: TextStyle(
                                                              color: Color(
                                                                0xFF333333,
                                                              ),
                                                              fontSize: controller.textSize.value.toDouble(),
                                                            ),
                                                          ),),
                                                      ],),
                                                    SizedBox(
                                                      height: 6,),
                                                    Row(
                                                      children: [
                                                        Expanded(
                                                          child: Text(
                                                          item['tgtText'],
                                                            style: TextStyle(
                                                              // color: Colors.red,
                                                              color: Color(
                                                                0xFF333333,
                                                              ),
                                                              fontSize: controller.textSize.value.toDouble(),
                                                            ),
                                                          ),),
                                                      ],)

                                                  ],),
                                                padding: EdgeInsets
                                                    .fromLTRB(
                                                  16, 8, 8, 8,),
                                                margin: EdgeInsets
                                                    .fromLTRB(
                                                  16, 16, 20, 8,),
                                              ),
                                            ],)

                                        );
                                      }
                                    }
                                    )
                                        .toList(),
                                  ),
                                )
                              ],
                            ))
                          ],
                        ),
                      ), ),

                  ],
                ),
              ),
            ),
            Container(
              color: Colors.white,
              width: Get.width,
              // 该值跟calling_view的Get.height - 130相关
              height: 104.h,
              child: Column(
               children: [
                 Obx(()=>Padding(
                   padding: EdgeInsets.only(top: 16.h),
                   child: Center(
                     child: controller.isEnter.value?new TimeText(startTime: controller.startTime.value):Text('00:00',
                       textAlign: TextAlign.center,
                       style: TextStyle(
                         fontSize: 14,
                         color: Color((0xFF333333)),
                         fontWeight: FontWeight.w700,
                       ),
                     ),
                   ),
                 )),
                 new VideoCallFooter(
                   onHandUp: controller.handleHandOff,
                   // onSwitchCamera: controller.handleSwitchCamera,
                   onMuteMic: controller.handleMuteMic,
                   onMuteSpeaker: controller.handleMuteSpeaker,
                   onMuteVideo: controller.handleMuteLocalVideo,
                   isOpenSpeaker: controller.isOpenSpeaker.value,
                   isOpenMic: controller.isOpenMic.value,
                   isOpenCamera: controller.isOpenCamera.value,
                   textSize: controller.textSize.value,
                   callType: controller.callType,
                   changeSize:controller.changeFontSize,

                 ),
               ],
              )

            ),
          ],
        ),
      ),
    );
  }
}
